var comicSrcRegEx = new RegExp("http://imgs.xkcd.com/comics/.*\.(png|bmp|img|jpeg|jpg)");	//if you are an img in the comic folder, then u are a comic
var xkcdAltLogoRegEx = new RegExp("logo");	//xkcd logo img has 'logo' in the alt text
var Imgs = document.getElementsByTagName('img');
var xkcdLogoSrc = "";
var comicAltText = "";		//this will be used to put the alt txt on the front page.
var body = "<body style='background-color:white'><div style='float:left;width:auto'>";

for (var i = 0; i < Imgs.length; i++ ){
	if(xkcdAltLogoRegEx.test(Imgs[i].alt)){			//test for logo
		//this is probaby poor coding, but we are going to assume the logo is going to be found BEFORE we find the comic
		body += "<img style='display:block;margin: 0 auto' src='"+Imgs[i].src+"' />";
	}else if(comicSrcRegEx.test(Imgs[i].src)){		//test for comic
		//when we find the comic, setup the page.
		body += "<h1 style='margin:15px auto'>"+Imgs[i].alt+"</h1><br />";
		body += "<img src='"+Imgs[i].src+"' /><br />";
		body += '<p style="margin:15px auto;width:'+Imgs[i].width+'">'+Imgs[i].title+'</p>';	//we set the width so that the title text falls within the picture.
		
		comicAltText =Imgs[i].title;
	}
}
//we should be done making the body... so, close it up
body += "</div></body>";

//lets get to why we came... add the print menu item to the menus, and make sure when we click it, that we get a printable page.
var menuDivs = document.getElementsByClassName('menuCont');  //these are 2 divs with class menuCont
for(var i = 0; i < menuDivs.length; i++) {
	var menuDiv = menuDivs[i];
	var ul = menuDiv.children[0];
	
	//at the 2nd div, we want to add the alt text
	if(i==1){
		var altText = document.createElement('p');
		altText.innerHTML=comicAltText;
		menuDiv.insertBefore(altText,ul);
	}
	
	//Make and insert a print menu button.
	//Add this comment to test svn.
	var printMenuItem = document.createElement('li');
	printMenuItem.innerHTML = "<a href='#'>Print</a>";
	ul.appendChild(printMenuItem);
	
	//Add an eventlistener to the new menu item. This will load the print page. 
	printMenuItem.addEventListener("click",function(){
		var html = "<html><head>";
		
		var cssRegEx = new RegExp("http://imgs.xkcd.com/.*\.css"); //accept any css file in any folder, so long as said folder is from xkcd.
		var styles = document.styleSheets;
		for(var j =0; j< styles.length; j++){
			if(cssRegEx.test(styles[j].href)){
				html +='<link rel="stylesheet" type="text/css" href="'+styles[j].href+'" media="screen" title="Default">'
			}
		}
		html += "</head>"+body+"</html>";
		
		var doc=document.open("text/html");
		doc.write(html);
		doc.close();
		
						
		setTimeout('window.print()',500);
		}, false);
}